package leetcode.code1073;

import java.util.ArrayList;
import java.util.List;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int[] addNegabinary(int[] arr1, int[] arr2) {
		int len1 = arr1.length, len2 = arr2.length;
		int p1 = len1 - 1, p2 = len2 - 1;
		List<Integer> ans = new ArrayList<>();
		int[] carry = new int[] { 0, 0 };
		while (p1 >= 0 || p2 >= 0) {
			int[] n1 = new int[] { p1 - 1 >= 0 ? arr1[p1 - 1] : 0, p1 >= 0 ? arr1[p1] : 0 };
			int[] n2 = new int[] { p2 - 1 >= 0 ? arr2[p2 - 1] : 0, p2 >= 0 ? arr2[p2] : 0 };
			int[] a1 = add(n1, n2);
			int[] a2 = add(new int[] { a1[2], a1[3] }, carry);
			int[] a3 = add(new int[] { a1[0], a1[1] }, new int[] { a2[0], a2[1] });
			carry = new int[] { a3[2], a3[3] };
			ans.add(a2[3]);
			ans.add(a2[2]);
			p1 -= 2;
			p2 -= 2;
		}
		if (carry[0] != 0) {
			ans.add(carry[1]);
			ans.add(carry[0]);
		} else if (carry[1] != 0) {
			ans.add(carry[1]);
		}
		ans = ans.subList(0, ans.lastIndexOf(1) + 1);
		if (ans.size() == 0) {
			return new int[] { 0 };
		}
		int[] ret = new int[ans.size()];
		for (int i = 0; i < ret.length; i++) {
			ret[i] = ans.get(ans.size() - i - 1);
		}
		return ret;
	}

	private int[] add(int[] n1, int[] n2) {
		int[] n = new int[] { n1[0] + n2[0], n1[1] + n2[1] };
		int a = n[0], b = n[1];
		if (a == 0 && b == 2) {
			return new int[] { 0, 1, 1, 0 };
		} else if (a == 1 && b == 2) {
			return new int[] { 0, 0, 0, 0 };
		} else if (a == 2 && b == 0) {
			return new int[] { 1, 1, 0, 0 };
		} else if (a == 2 && b == 1) {
			return new int[] { 1, 1, 0, 1 };
		} else if (a == 2 && b == 2) {
			return new int[] { 0, 0, 1, 0 };
		} else {
			return new int[] { 0, 0, a, b };
		}
	}

	@Override
	public void debug4() {
		this.addNegabinary(H.str2array3("[1,1,0]"), H.str2array3("[1,1,0]"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
